const calculatePetStatus = (pet) => {
    const now = new Date();
    const hoursSinceLastFed = pet.lastFed ? 
        (now - new Date(pet.lastFed)) / (1000 * 60 * 60) : 24;
    const hoursSinceLastTrained = pet.lastTrained ? 
        (now - new Date(pet.lastTrained)) / (1000 * 60 * 60) : 24;

    // 每8小时降低10点饥饿度
    let hunger = Math.max(0, pet.hunger - Math.floor(hoursSinceLastFed / 8) * 10);
    
    // 饥饿会影响快乐度，每降低20点饥饿度，快乐度降低5点
    let happiness = Math.max(0, pet.happiness - Math.floor((100 - hunger) / 20) * 5);
    
    // 缺乏训练会降低体力值，每24小时降低5点
    let energy = Math.max(0, pet.energy - Math.floor(hoursSinceLastTrained / 24) * 5);

    return {
        hunger,
        happiness,
        energy,
        needsFeeding: hunger < 50,
        needsTraining: energy > 10 && hunger > 5,
        status: getPetStatus(hunger, happiness, energy)
    };
};

const getPetStatus = (hunger, happiness, energy) => {
    if (hunger < 20 || happiness < 20 || energy < 20) {
        return 'unhealthy';
    }
    if (hunger < 50 || happiness < 50 || energy < 50) {
        return 'normal';
    }
    return 'happy';
};

const calculateTrainingEffect = (pet) => {
    const baseExp = 10;
    const happinessMultiplier = pet.happiness / 100;
    const energyMultiplier = pet.energy / 100;
    
    return Math.floor(baseExp * happinessMultiplier * energyMultiplier);
};

const generatePetAppearance = (species) => {
    const appearances = {
        cat: {
            colors: ['orange', 'black', 'white', 'gray', 'brown'],
            patterns: ['solid', 'striped', 'spotted', 'calico'],
            accessories: ['bow', 'bell', 'scarf', 'none']
        },
        dog: {
            colors: ['brown', 'black', 'white', 'golden', 'gray'],
            patterns: ['solid', 'spotted', 'patched'],
            accessories: ['collar', 'bandana', 'hat', 'none']
        },
        rabbit: {
            colors: ['white', 'brown', 'black', 'gray'],
            patterns: ['solid', 'spotted', 'dutch'],
            accessories: ['bow', 'carrot charm', 'none']
        }
    };

    const speciesData = appearances[species] || appearances.cat;
    return {
        color: speciesData.colors[Math.floor(Math.random() * speciesData.colors.length)],
        pattern: speciesData.patterns[Math.floor(Math.random() * speciesData.patterns.length)],
        accessory: speciesData.accessories[Math.floor(Math.random() * speciesData.accessories.length)]
    };
};

module.exports = {
    calculatePetStatus,
    calculateTrainingEffect,
    generatePetAppearance,
    getPetStatus
};